﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Isha.Entities;
using Isha.Framework.Web;
using Isha.Infrastructure;
using Isha.Repositories;
using Isha.Repositories.Infrastructure;
using Isha.Services;
using Microsoft.Practices.Unity;
using Isha.Extensions;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System;

namespace Isha.Web.Mvc
{
    public sealed class IshaApplication : System.Web.HttpApplication
    {
        [ImportMany]
        public IEnumerable<IModule> ModuleList { get; set; }

        public static void Ready(RouteCollection routes)
        {
            Database.SetInitializer(new IshaDatabaseInitializer());
            DependencyResolver.SetResolver(new UnityDependencyResolver(IshaBuilder.Container));
            BindUnityContainer(IshaBuilder.Container);
                       

            IshaApplication ishaModules = new IshaApplication();
            var catalog = new AssemblyCatalog(AppDomain.CurrentDomain.BaseDirectory + @"\Bin\Isha.Extensions.Modules.dll");
            var container = new CompositionContainer(catalog);
            container.ComposeParts(ishaModules);

            foreach (var item in ishaModules.ModuleList)
            {
                item.Build();
            }

            if (routes != null)
            {
                routes.Add(new IshaRoute());
            }
        }

        private static void BindUnityContainer(IUnityContainer container)
        {
            // Cache and Others
            container
                .RegisterInstance<IshaModel>(new IshaModel(), new HttpContextLifetimeManager<IshaModel>())
                .RegisterInstance<IEnumerable<Part>>(container.Resolve<IPartService>().GetParts())
                .RegisterInstance<IEnumerable<ContentItem>>("Navigation", container.Resolve<IContentItemService>().FetchContentItemsByParent(1));
        }
    }
}
